//package com.turing.post.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;

/**
 * Dependency
 * 
 * @author yangxinbin
 */
public class Dependency implements AnnotationVisitor, SignatureVisitor,
		ClassVisitor, FieldVisitor, MethodVisitor {
	/* 外部依赖类 */
	private HashSet<String> dependClass = new HashSet<String>();

	/* 是否是Stateless EJB */
	private boolean isStatelessEJB = false;

	/* 是否是Stateful EJB */
	private boolean isStatefulEJB = false;

	/* 是否是MessageDriven EJB */
	private boolean isMessageDrivenEJB = false;

	/* 是否是Entity Bean */
	private boolean isEntity = false;

	/* 是否有主键 */
	private boolean hasPrimaryKey = false;

	/* 主键的类名 */
	private String primaryKeyClass = null;

	/* 过滤器 */
	private String filterPrefix = null;

	/* 类自身名称 */
	private String selfName = null;

	private String lastAnnotationClassName = "";

	public boolean hasPrimaryKey() {
		return hasPrimaryKey;
	}

	public String getPrimaryKeyClass() {
		return primaryKeyClass;
	}

	public static Dependency getDependency(String clsfilename, String prefixName)
			throws IOException {
		Dependency dependency = new Dependency();

		ClassReader classReader = new ClassReader(new FileInputStream(
				clsfilename));

		dependency.setFilterPrefix(prefixName);

		classReader.accept(dependency, 0);

		return dependency;
	}

	public String getSelfName() {
		return selfName;
	}

	public HashSet<String> getDependClass() {
		return dependClass;
	}

	public void setFilterPrefix(String filterPrefix) {
		this.filterPrefix = filterPrefix;
	}

	public String getFilterPrefix() {
		return filterPrefix;
	}

	public boolean isStatelessEJB() {
		return isStatelessEJB;
	}

	public boolean isStatefulEJB() {
		return isStatefulEJB;
	}

	public boolean isMessageDrivenEJB() {
		return isMessageDrivenEJB;
	}

	public boolean isEJB() {
		return (isStatelessEJB || isStatefulEJB || isMessageDrivenEJB);
	}

	public boolean isEntity() {
		return isEntity;
	}

	// ClassVisitor - 类观察者

	public void visit(final int version, final int access, final String name,
			final String signature, final String superName,
			final String[] interfaces) {

		// 判断自身的名称
		selfName = name.replace("/", ".");

		if (signature == null) {
			addInternalName(superName);
			addInternalNames(interfaces);
		} else {
			addSignature(signature);
		}
	}

	public AnnotationVisitor visitAnnotation(final String desc,
			final boolean visible) {
		if (visible) {
			if (!isEntity)
				isEntity = desc.equals("Ljavax/persistence/Entity;");
			if (!isStatelessEJB)
				isStatelessEJB = desc.equals("Ljavax/ejb/Stateless;");
			if (!isStatefulEJB)
				isStatefulEJB = desc.equals("Ljavax/ejb/Stateful;");
			if (!isMessageDrivenEJB)
				isMessageDrivenEJB = desc.equals("Ljavax/ejb/MessageDriven;");
			lastAnnotationClassName = desc;
		}
		//System.out.println("visitAnnotation:" + desc + " visible: " + visible
		//		+ " isEJB: " + isEJB());
		addDesc(desc);
		return this;
	}

	public void visitAttribute(final Attribute attr) {
	}

	public FieldVisitor visitField(final int access, final String name,
			final String desc, final String signature, final Object value) {
		if (signature == null) {
			addDesc(desc);
		} else {
			addTypeSignature(signature);
		}
		if (value instanceof Type) {
			addType((Type) value);
		}
		return this;
	}

	public MethodVisitor visitMethod(final int access, final String name,
			final String desc, final String signature, final String[] exceptions) {
		if (signature == null) {
			addMethodDesc(desc);
		} else {
			addSignature(signature);
		}
		addInternalNames(exceptions);
		return this;
	}

	public void visitSource(final String source, final String debug) {
	}

	public void visitInnerClass(final String name, final String outerName,
			final String innerName, final int access) {
		// addName( outerName);
		// addName( innerName);
	}

	public void visitOuterClass(final String owner, final String name,
			final String desc) {
		// addName(owner);
		// addMethodDesc(desc);
	}

	// MethodVisitor - 方法观察者

	public AnnotationVisitor visitParameterAnnotation(final int parameter,
			final String desc, final boolean visible) {
		addDesc(desc);
		return this;
	}

	public void visitTypeInsn(final int opcode, final String type) {
		addType(Type.getObjectType(type));
	}

	public void visitFieldInsn(final int opcode, final String owner,
			final String name, final String desc) {
		addInternalName(owner);
		addDesc(desc);
	}

	public void visitMethodInsn(final int opcode, final String owner,
			final String name, final String desc) {
		addInternalName(owner);
		addMethodDesc(desc);
	}

	public void visitLdcInsn(final Object cst) {
		if (cst instanceof Type) {
			addType((Type) cst);
		}
	}

	public void visitMultiANewArrayInsn(final String desc, final int dims) {
		addDesc(desc);
	}

	public void visitLocalVariable(final String name, final String desc,
			final String signature, final Label start, final Label end,
			final int index) {
		addTypeSignature(signature);
	}

	public AnnotationVisitor visitAnnotationDefault() {
		return this;
	}

	public void visitCode() {
	}

	public void visitFrame(final int type, final int nLocal,
			final Object[] local, final int nStack, final Object[] stack) {
	}

	public void visitInsn(final int opcode) {
	}

	public void visitIntInsn(final int opcode, final int operand) {
	}

	public void visitVarInsn(final int opcode, final int var) {
	}

	public void visitJumpInsn(final int opcode, final Label label) {
	}

	public void visitLabel(final Label label) {
	}

	public void visitIincInsn(final int var, final int increment) {
	}

	public void visitTableSwitchInsn(final int min, final int max,
			final Label dflt, final Label[] labels) {
	}

	public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
			final Label[] labels) {
	}

	public void visitTryCatchBlock(final Label start, final Label end,
			final Label handler, final String type) {
		addInternalName(type);
	}

	public void visitLineNumber(final int line, final Label start) {
	}

	public void visitMaxs(final int maxStack, final int maxLocals) {
	}

	// AnnotationVisitor

	public void visit(final String name, final Object value) {
		if (name != null
				&& value != null
				&& name.equals("value")
				&& lastAnnotationClassName
						.equals("Ljavax/persistence/IdClass;")) {
			hasPrimaryKey = true;
			primaryKeyClass = ((Type) value).getClassName();
		}

		if (value instanceof Type) {
			addType((Type) value);
		}
	}

	public void visitEnum(final String name, final String desc,
			final String value) {
		addDesc(desc);
	}

	public AnnotationVisitor visitAnnotation(final String name,
			final String desc) {
		addDesc(desc);
		return this;
	}

	public AnnotationVisitor visitArray(final String name) {
		return this;
	}

	// SignatureVisitor

	String signatureClassName;

	public void visitFormalTypeParameter(final String name) {
	}

	public SignatureVisitor visitClassBound() {
		return this;
	}

	public SignatureVisitor visitInterfaceBound() {
		return this;
	}

	public SignatureVisitor visitSuperclass() {
		return this;
	}

	public SignatureVisitor visitInterface() {
		return this;
	}

	public SignatureVisitor visitParameterType() {
		return this;
	}

	public SignatureVisitor visitReturnType() {
		return this;
	}

	public SignatureVisitor visitExceptionType() {
		return this;
	}

	public void visitBaseType(final char descriptor) {
	}

	public void visitTypeVariable(final String name) {
	}

	public SignatureVisitor visitArrayType() {
		return this;
	}

	public void visitClassType(final String name) {
		signatureClassName = name;
		addInternalName(name);
	}

	public void visitInnerClassType(final String name) {
		signatureClassName = signatureClassName + "$" + name;
		addInternalName(signatureClassName);
	}

	public void visitTypeArgument() {
	}

	public SignatureVisitor visitTypeArgument(final char wildcard) {
		return this;
	}

	// common

	public void visitEnd() {
	}

	// ---------------------------------------------

	private void addName(String name) {
		if (name == null)
			return;

		// 将内部名称由/转为.
		name = name.replace("/", ".");

		// 忽略自身
		if (name.equals(selfName))
			return;

		// 如果设置了过滤器,则不满足的类将不进入类的外部依赖集合
		if (filterPrefix != null || filterPrefix.length() > 0) {
			if (!name.startsWith(filterPrefix))
				return;
		}

		// 如果不包含则加入到集合中
		if (!dependClass.contains(name))
			dependClass.add(name);
	}

	private void addInternalName(final String name) {
		if (name != null)
			addType(Type.getObjectType(name));
	}

	private void addInternalNames(final String[] names) {
		for (int i = 0; names != null && i < names.length; i++) {
			addInternalName(names[i]);
		}
	}

	private void addDesc(final String desc) {
		addType(Type.getType(desc));
	}

	private void addMethodDesc(final String desc) {
		addType(Type.getReturnType(desc));
		Type[] types = Type.getArgumentTypes(desc);
		for (int i = 0; i < types.length; i++) {
			addType(types[i]);
		}
	}

	private void addType(final Type t) {
		switch (t.getSort()) {
		case Type.ARRAY:
			addType(t.getElementType());
			break;
		case Type.OBJECT:
			addName(t.getInternalName());
			break;
		}
	}

	private void addSignature(final String signature) {
		if (signature != null) {
			new SignatureReader(signature).accept(this);
		}
	}

	private void addTypeSignature(final String signature) {
		if (signature != null) {
			new SignatureReader(signature).acceptType(this);
		}
	}
}
